package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.AssertUtils;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningRecordFormDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import com.tianji.learning.utils.LearningRecordDelayTaskHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.tianji.learning.enums.SectionType.VIDEO;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2024-08-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {

    private final ILearningLessonService lessonService;
    private final CourseClient courseClient;
    private final LearningRecordDelayTaskHandler taskHandler;

    /**
     * 1、查询当前用户指定课程的学习进度 （Day3 - 随堂1）
     *
     * @param courseId 课程ID
     * @return
     */
    @Override
    public LearningLessonDTO queryLearningRecordByCourse(Long courseId) {
        log.info("查询当前用户指定课程：{} 的学习进度", courseId);
        // 1、根据 userId和courseId 查询课表
        // select * from learning_lesson where user_id = ? and course_id = ?
        LearningLesson lesson = lessonService.queryLessonByCourseIdAndUserId(courseId, UserContext.getUser());
        if (ObjectUtil.isEmpty(lesson)) {
            return null;
        }

        // 2、根据课表id查询课表下的学习记录
        // select * from learning_record where lesson_id = ?
        List<LearningRecord> records = this.lambdaQuery().eq(LearningRecord::getLessonId, lesson.getId()).list();

        // 3、组长DTO并返回
        return LearningLessonDTO.of(lesson.getId(), lesson.getLatestSectionId(),
                BeanUtils.copyList(records, LearningRecordDTO.class));
    }

    /**
     * 2、提交学习进度（Day3 - 随堂2）
     *
     * @param formDTO
     */
    @Override
    @Transactional
    public void addLearningRecord(LearningRecordFormDTO formDTO) {
        // 1、处理学习记录
        /*boolean firstFinished;
        if (formDTO.getSectionType() == VIDEO) {
            // 1.1、处理视频学习记录
            firstFinished = handleVideoRecord(formDTO);
        } else {
            // 1.2、处理考试学习记录
            firstFinished = handleExamRecord(formDTO);
        }*/

        boolean firstFinished = formDTO.getSectionType() == VIDEO ? handleVideoRecord(formDTO) : handleExamRecord(formDTO);
        if(!firstFinished && formDTO.getDuration() == -1){   // 如果firstFinished为false，并且duration为-1证明本次是暂存进度至redis，无需处理课表数据，而是等待延时检测任务处理
            return;
        }

        // 2、处理课表数据
        handleLearningLesson(formDTO, firstFinished);
    }

    /**
     * 处理课表数据
     *
     * @param formDTO       前端参数
     * @param firstFinished 是否是第一次学完当前小节
     */
    private void handleLearningLesson(LearningRecordFormDTO formDTO, boolean firstFinished) {
        // 1、查询课表数据（已学习小节数、课表ID）
        LearningLesson lesson = this.lessonService.getById(formDTO.getLessonId());
        AssertUtils.isNotNull(lesson,"课表数据不存在，无法更新数据");

        // 2、判断是否有新的完成小节
        boolean allLearned = false;
        if (firstFinished) {
            // 2.1、查询课程数据
            CourseFullInfoDTO courseInfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
            AssertUtils.isNotNull(lesson,"课程数据不存在，无法更新数据");

            // 2.2、比较课程是否已经全部学完（已学完小节数 + 1 >= 课程总小节数）
            allLearned = lesson.getLearnedSections() + 1 >= courseInfo.getSectionNum();
        }

        // 3、更新课表数据
        boolean updateResult = this.lessonService.lambdaUpdate()
                .set(LearningLesson::getLatestSectionId, formDTO.getSectionId())  //最近学习小节ID
                .set(LearningLesson::getLatestLearnTime, formDTO.getCommitTime()) //最近学习时间
                //.set(firstFinished,LearningLesson::getLearnedSections, lesson.getLearnedSections() + 1) // 如果该小节已学完，将已学习小节数 +1
                .setSql(firstFinished, "learned_sections = learned_sections + 1") // 如果该小节已学完，将已学习小节数 +1
                .set(lesson.getStatus() == LessonStatus.NOT_BEGIN , LearningLesson::getStatus, LessonStatus.LEARNING)
                .set(allLearned, LearningLesson::getStatus, LessonStatus.FINISHED)
                .eq(LearningLesson::getId, lesson.getId())
                .update();
        if (!updateResult) {
            throw new DbException("修改课表数据失败！");
        }

    }

    /**
     * 处理考试学习记录
     *
     * @param formDTO
     * @return 是否是第一次学完
     */
    private boolean handleExamRecord(LearningRecordFormDTO formDTO) {
        // 1、将 DTO 转换为 PO
        LearningRecord record = BeanUtils.copyBean(formDTO, LearningRecord.class);

        // 2、填充缺失的数据
        record.setUserId(UserContext.getUser());
        record.setFinished(true);
        record.setFinishTime(formDTO.getCommitTime());

        // 3、写入数据库
        boolean result = save(record);
        if (!result) {
            throw new DbException("新增考试记录失败！");
        }

        // 4、返回标识
        return true;
    }

    /**
     * 处理视频学习记录
     *
     * @param formDTO
     * @return
     */
    private boolean handleVideoRecord(LearningRecordFormDTO formDTO) {
        // 1、查询旧的学习记录
        LearningRecord oldRecord = this.queryOldRecord(formDTO.getLessonId(),formDTO.getSectionId());

        // 2、判断学习记录是否存在
        if (ObjectUtil.isEmpty(oldRecord)) {
            // 3、如果不存在，新增学习记录
            // 3.1、将 DTO 转换为 PO
            LearningRecord record = BeanUtils.copyBean(formDTO, LearningRecord.class);

            // 3.2、填充缺失的数据
            record.setUserId(UserContext.getUser());

            // 3.3、写入数据库
            boolean result = save(record);
            if (!result) {
                throw new DbException("新增学习记录失败！");
            }

            // 3.4、返回标识
            return false;
        }

        // 4、如果存在，更新学习记录
        // 4.1、判断是否是第一次学完当前小节
        boolean firstFinished = !oldRecord.getFinished() && formDTO.getMoment() << 1 >= formDTO.getDuration();

        // 4.2、如果是非第一次学完，将学习记录暂存至redis，并且提交一个延时检测任务
        if(!firstFinished){
            LearningRecord learningRecord = new LearningRecord();
            learningRecord.setLessonId(formDTO.getLessonId());
            learningRecord.setSectionId(formDTO.getSectionId());
            learningRecord.setId(oldRecord.getId());
            learningRecord.setMoment(formDTO.getMoment());
            learningRecord.setFinished(oldRecord.getFinished());
            taskHandler.addLearningRecordDelayCheckTask(learningRecord);
            formDTO.setDuration(-1);
            return false;
        }

        // 4.3、更新学习记录（一定要更新的字段：moment，第一次学完时更新两个字段：finished、finish_time）
        boolean updateResult = this.lambdaUpdate()
                .set(LearningRecord::getMoment, formDTO.getMoment())
                .set(LearningRecord::getFinished, true)
                .set(LearningRecord::getFinishTime, formDTO.getCommitTime())
                .eq(LearningRecord::getId, oldRecord.getId())
                .update();
        if (!updateResult) {
            throw new DbException("更新学习记录失败！");
        }

        // 4.4、清理redis缓存中的学习记录（目的是为了保证Redis双写一致性！）
        taskHandler.cleanLearningRecordCache(formDTO.getLessonId(),formDTO.getSectionId());
        return true;
    }

    /**
     * 查询旧的学习记录
     * @param lessonId  课表ID
     * @param sectionId 小节ID
     * @return
     */
    private LearningRecord queryOldRecord(Long lessonId, Long sectionId) {
        // 1、先从缓存中查询学习记录
        LearningRecord oldRecord = taskHandler.readLearningRecordFromCache(lessonId,sectionId);

        // 2、如果存在，直接返回
        if(ObjectUtil.isNotEmpty(oldRecord)){
            return oldRecord;
        }

        // 3、如果不存在，则查询数据库，并将结果放入缓存
        // select * from learing_record where lesson_id ? and section_id = ?
        oldRecord = this.lambdaQuery().eq(LearningRecord::getLessonId, lessonId)
                .eq(LearningRecord::getSectionId, sectionId).one();

        if(ObjectUtil.isEmpty(oldRecord)){
            return null;  // 不能抛异常，要作为调用者处理后续代码逻辑的判断依据
        }
        taskHandler.writeLearningRecordToCache(oldRecord);

        // 4、返回record
        return oldRecord;
    }
}
